package cn.huaguo.domain.task.service;

import cn.huaguo.domain.order.model.entity.OrderEntity;
import cn.huaguo.domain.order.model.valobj.OrderStatusVO;
import cn.huaguo.domain.task.model.aggragate.PublishTradeTaskAggregate;
import cn.huaguo.domain.task.model.entity.PublishTaskEntity;
import cn.huaguo.domain.task.model.entity.TaskEntity;
import cn.huaguo.domain.task.model.valobj.TaskStatusVO;
import cn.huaguo.domain.task.repository.ITaskRepository;
import cn.huaguo.types.context.BaseContext;
import org.apache.commons.lang3.RandomStringUtils;

import javax.annotation.Resource;

/**
 * @Description 任务服务抽象类 定义流程
 * @Author wangqian
 * @Date 2024/8/9
 */
public abstract class AbstractTaskService implements ITaskService {
    @Resource
    private ITaskRepository taskRepository;

    /**
     * 发布平台交易型任务
     *
     * @param taskEntity 任务实体
     */
    @Override
    public PublishTaskEntity publishTradeTask(TaskEntity taskEntity) {
        String currentUserId = BaseContext.getCurrentId();
        String orderId = RandomStringUtils.randomNumeric(16);
        // 设置任务基础信息
        taskEntity.setCreateUserId(currentUserId);
        taskEntity.setTaskStatus(TaskStatusVO.CREATE.getCode());

        // 构建订单对象
        OrderEntity orderEntity = OrderEntity.builder()
                .orderId(orderId)
                .createUserId(currentUserId)
                .orderStatus(OrderStatusVO.CREATE.getCode())
                .orderAmount(taskEntity.getTaskReward())
                .build();

        // 构建发布任务聚合对象
        PublishTradeTaskAggregate publishTradeTaskAggregate = PublishTradeTaskAggregate.builder()
                .userId(currentUserId)
                .taskEntity(taskEntity)
                .orderEntity(orderEntity)
                .build();

        // 保存任务 保存订单
        PublishTaskEntity publishTaskEntity = this.savePublishTaskAggregate(publishTradeTaskAggregate);

        // 创建支付
        this.createPay(publishTaskEntity);

        return publishTaskEntity;
    }

    protected abstract void createPay(PublishTaskEntity publishTaskEntity);

    protected abstract PublishTaskEntity savePublishTaskAggregate(PublishTradeTaskAggregate publishTradeTaskAggregate);
}
